<template>
  <div class="app-container">
    <el-card shadow="never" class="mb-10" body-style="padding-bottom: 2px">
      <SearchBar
        :search-items="searchItems"
        :initial-values="initialValues"
        @search="handleSearch"
        @reset="handleReset"
      />
    </el-card>
    <el-card shadow="never" class="mb-10">
      <div>
        <div class="flex items-center">
          <div class="w-10 h-10 bg-accent-color" />
          <div class="text-16 text-333333 font-bold ml-10">
            {{ dataStatisticsType === 1 ? "调用量" : "消息推送" }}
          </div>
          <div class="text-12 text-666666">（次）</div>
        </div>
        <LineChart
          :loading="isLoading"
          :legend-data="legendData"
          :x-axis-data="xAxisData"
          :series-data="seriesData"
        />
      </div>
    </el-card>
    <el-card shadow="never" class="mb-10">
      <div>
        <div class="flex items-center mb-20">
          <div class="w-10 h-10 bg-accent-color" />
          <div class="text-16 text-333333 font-bold ml-10">每日详细数据</div>
        </div>
        <PaginationTable
          v-loading="pageLoading"
          :table-data="tableData"
          :columns="columns"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @page-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import SearchBar, { SearchItem } from "@/views/templatePage/SearchBar/index.vue";
import LineChart from "@/views/templatePage/ECharts/index.vue";
import { EChartsOption } from "echarts";
import DataManageAPI, { ResponseListFormData, ResponseListInfo } from "@/api/dataManage";
import { formatDate, removeFields } from "@/utils";
import PaginationTable, { TableColumn } from "@/views/templatePage/PaginationTable/index.vue";
// 定义 props
const props = defineProps({
  // 数据统计类型 1-API调用统计 2-消息推送统计
  dataStatisticsType: {
    type: Number,
    default: 1,
  },
});
// 搜索项配置
const searchItems: SearchItem[] = [
  {
    prop: "timeList",
    startTime: "beginDate",
    endTime: "endDate",
    label: "时间",
    type: "daterange",
    clearable: false,
    disabledDate: (time: Date) => {
      return time.getTime() > Date.now();
    },
  },
];
// 初始值
const startDate = new Date();
startDate.setDate(startDate.getDate() - 7);
const beginDate = formatDate(startDate, "YYYY-MM-DD");
const endDate = formatDate(new Date(), "YYYY-MM-DD");
const initialValues = ref<Record<string, any>>({
  timeList: [beginDate, endDate],
  beginDate: beginDate,
  endDate: endDate,
});
// 处理搜索
const handleSearch = (form: Record<string, any>) => {
  initialValues.value = form;
  const beginDate = new Date(initialValues.value.beginDate);
  beginDate.setMonth(beginDate.getMonth() + 1);
  const endDate = new Date(initialValues.value.endDate).getTime();
  if (endDate > beginDate.getTime()) {
    ElMessage.warning("时间跨度最大为一个月");
    return;
  }
  getEChartsResponseList();
  handlePageChange(1);
};
// 处理重置
const handleReset = () => {
  initialValues.value.timeList = [beginDate, endDate];
  initialValues.value.beginDate = beginDate;
  initialValues.value.endDate = endDate;
  getEChartsResponseList();
  handlePageChange(1);
};

// 加载状态
const isLoading = ref(false);
// 定义series类型
interface SeriesInfo {
  // 名称
  name: string;
  // 类型
  type: string;
  // 数据
  data: number[];
}
// series数据
const seriesData = ref<SeriesInfo[]>([]);
// xAxis数据
const xAxisData = ref<string[]>([]);
// legend数据
const legendData = ref<string[]>([]);
// 获取ECharts数据
const getEChartsResponseList = () => {
  if (isLoading.value) return;
  isLoading.value = true;
  const param: Record<string, any> = removeFields(initialValues.value, ["timeList"]);
  DataManageAPI.getEChartsResponseList(param as ResponseListFormData)
    .then((data) => {
      isLoading.value = false;
      const legend: string[] = [];
      const series: SeriesInfo[] = [];
      let lineChartList: OptionType[] = [
        { label: "调用总量", value: "tr", show: props.dataStatisticsType === 1 },
        { label: "成功数量", value: "sr", show: props.dataStatisticsType === 1 },
        { label: "失败数量", value: "fr", show: props.dataStatisticsType === 1 },
        { label: "消息推送总数", value: "te", show: props.dataStatisticsType === 2 },
        { label: "消息推送成功数", value: "se", show: props.dataStatisticsType === 2 },
        { label: "消息推送失败数", value: "fe", show: props.dataStatisticsType === 2 },
      ];
      lineChartList
        .filter((item) => item.show)
        .forEach((item) => {
          legend.push(item.label);
          const lineChartParam: SeriesInfo = {
            name: item.label,
            type: "line",
            data: [],
          };
          data.forEach((cItem: ResponseListInfo) => {
            lineChartParam.data.push(cItem[item.value]);
          });
          series.push(lineChartParam);
        });
      const xAxis: string[] = [];
      data.forEach((item) => {
        xAxis.push(item.d);
      });
      legendData.value = legend;
      xAxisData.value = xAxis;
      seriesData.value = series;
    })
    .catch(() => {
      isLoading.value = false;
    });
};

// 表格数据
const tableData = ref<ResponseListInfo[]>([]);
// 列配置
const columns: TableColumn[] = [
  {
    prop: "d",
    label: "日期",
    headerAlign: "left",
    align: "left",
    show: [1, 2].includes(props.dataStatisticsType),
  },
  { prop: "tr", label: "调用次数", show: props.dataStatisticsType === 1 },
  { prop: "sr", label: "调用成功次数", show: props.dataStatisticsType === 1 },
  { prop: "fr", label: "调用失败次数", show: props.dataStatisticsType === 1 },

  { prop: "te", label: "推送次数", show: props.dataStatisticsType === 2 },
  { prop: "se", label: "推送成功次数", show: props.dataStatisticsType === 2 },
  { prop: "fe", label: "推送失败次数", show: props.dataStatisticsType === 2 },
  {
    prop: "fr/tr",
    label: "调用失败率",
    headerAlign: "right",
    align: "right",
    show: props.dataStatisticsType === 1,
  },
  {
    prop: "fe/te",
    label: "推送失败率",
    headerAlign: "right",
    align: "right",
    show: props.dataStatisticsType === 2,
  },
].filter((item) => item.show) as TableColumn[];
// 分页相关
const total = ref<number>(100); // 总条数
const currentPage = ref<number>(1); // 当前页码
const pageSize = ref<number>(10); // 每页条数
// 处理页码变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  getTableResponseList();
};
// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  getTableResponseList();
};
// 页面加载状态
const pageLoading = ref<boolean>(false);
// 获取表格列表
const getTableResponseList = () => {
  if (pageLoading.value) return;
  pageLoading.value = true;
  const param: Record<string, any> = removeFields(initialValues.value, ["timeList"]);
  DataManageAPI.getTableResponseList({
    limit: pageSize.value,
    page: currentPage.value,
    ...param,
  } as ResponseListFormData)
    .then((data) => {
      pageLoading.value = false;
      total.value = data.total;
      pageSize.value = data.per_page;
      currentPage.value = data.current_page;
      tableData.value = data.data.map((item) => ({
        ...item,
        "fr/tr": item.tr !== 0 ? Number(Number(item.fr / item.tr).toFixed(2)) + "%" : "0%",
        "fe/te": item.te !== 0 ? Number(Number(item.fe / item.te).toFixed(2)) + "%" : "0%",
      }));
    })
    .catch(() => {
      pageLoading.value = false;
    });
};

onMounted(() => {
  getEChartsResponseList();
  getTableResponseList();
});
</script>

<style scoped lang="scss"></style>
